import numpy as np
import matplotlib.pyplot as plt

"""
Given a stock’s price history as a sequence,
and assuming that you are only allowed to make one purchase and one sale,
what is the maximum profit that can be obtained?
For example, given prices = (20, 18, 14, 17, 20, 21, 15),
the max profit would be 7, from buying at 14 and selling at 21.

The above example is copied from realpython.com
"""


def profit(prices):
    max_px = 0
    min_px = prices[0]
    for px in prices[1:]:
        min_px = min(min_px, px)
        max_px = max(px - min_px, max_px)
    return max_px


def main():
    prices = np.full(100, fill_value=np.nan)
    prices[[0, 25, 60, -1]] = [80., 30., 75., 50.]

    x = np.arange(len(prices))
    is_valid = ~np.isnan(prices)
    prices = np.interp(x=x, xp=x[is_valid], fp=prices[is_valid])
    prices += np.random.randn(len(prices)) * 2

    def pypl(prices):
        mn = np.argmin(prices)
        mx = mn + np.argmax(prices[mn:])
        # kw = {'markersize': 12, 'linestyle': ''}
        kw = {'markersize': 5, 'marker': 'o'}

        fig, ax = plt.subplots()
        ax.plot(prices)
        ax.set_title('Prices History')
        ax.set_xlabel('Time')
        ax.set_ylabel('Price')
        ax.plot(mn, prices[mn], color='green', **kw)
        ax.plot(mx, prices[mx], color='red', **kw)
        return

    pypl(prices)
    plt.show()

    return


if __name__ == '__main__':
    prices = (20, 18, 14, 17, 20, 21, 15, 30)
    print(profit(prices))

    main()
